package com.jcoinexchange.web.util;

import org.apache.commons.text.StringSubstitutor;

import java.util.HashMap;
import java.util.Map;

/**
 * @desc 字符串formatter
 *
 * @author tony
 * @createDate 2024/4/8 11:02 上午
 */
public class StringFormatUtil {

    /**
     * 使用: StringFormatUtil.format("hello {} world {}", "tony", "here"); ==>  hello tony world here
     * @param template
     * @param values
     * @return
     */
    public static String format(String template, Object... values) {
        Map<String, String> valuesMap = new HashMap<>();
        // 将每个 `{}` 替换为一个带索引的占位符 `{0}`, `{1}`, etc.
        String processedTemplate = template;
        int placeholderIndex = 0;
        while (processedTemplate.contains("{}") && placeholderIndex < values.length) {
            processedTemplate = processedTemplate.replaceFirst("\\{\\}", "{" + placeholderIndex + "}");
            valuesMap.put(String.valueOf(placeholderIndex), values[placeholderIndex].toString());
            placeholderIndex++;
        }
        StringSubstitutor stringSubstitutor = new StringSubstitutor(valuesMap,"{","}");
        return stringSubstitutor.replace(processedTemplate);
    }
}
